import Mock from "mockjs";
// get请求从config.url获取参数, post从config.body中获取参数
function param2Obj(url){
  const search = url.split('?')[1]
  if (!search){
    return {}
  }
  return JSON.parse(
    '{"'+
    decodeURIComponent(search)
    .replace(/"/g, '\\"')
    .replace(/&/g,'","')
    .replace(/=/g,'":"') +
    '"}'
  )
}

let list = []
const count = 200
// 模拟200条用户数据
for (let i = 0; i < count; i++) {
  list.push(
    Mock.mock({
      id: Mock.Random.guid(),
      name: Mock.Random.cname(),
      addr: Mock.mock('@county(true)'),
      'age|16-100': 1,
      birth: Mock.Random.date(),
      sex: Mock.Random.integer(0, 1)
    })
  )
}


export default {
  /**
   * 获取列表
   * 要带参数 name, page,limit; name可选, page,limit有默认值
   * @param name
   * @param page
   * @param limit
   * @returns {code:number, count:number, dataz}
   */
  getUserData: (config) => {
    const {name, page=1, limit=10} = param2Obj(config.url)
    const mockList = list.filter(user => !name || user.name.includes(name));
    // 分页
    const pageList = mockList.filter((item, index) => index < limit * page && index >= limit * (page - 1))

    return {
      code: 200,
      data: {
        list: pageList,
        count: mockList.length
      }
    }
  },
  /**
   * 删除
   * @param id
   * @returns {*}
   */
  deleteUser: config => {
    const {id} = param2Obj(config.url)

    if (!id) {
      return {
        code: -999,
        message: '参数不正确'
      }
    } else {
      list = list.filter(u => u.id !== id)
      return {
        code: 200,
        message: '删除成功'
      }
    }
  },
  /**
   * 增加用户
   * @param name, addr, age, birth, sex
   * @returns {code: number, data: {message: string}}
   */
  addUser: config => {
    const {name, addr, age, birth, sex} = JSON.parse(config.body)
    list.unshift({
      id: Mock.Random.guid(),
      name: name,
      addr: addr,
      age: age,
      birth: birth,
      sex: sex
    })
    return {
      code: 200,
      data: {
        message: '添加成功'
      }
    }
  },
    /**
   * 修改用户
   * @param name, addr, age, birth, sex
   * @returns {code: number, data: {message: string}}
   */
    editUser: config => {
      const {id, name, addr, age, birth, sex} = JSON.parse(config.body)
      const sex_num = parseInt(sex) 
      list.some(item => {
        if (item.id === id) {
          item.name = name
          item.addr = addr
          item.age = age
          item.birth = birth
          item.sex = sex_num
          return true
        }
      })
      return {
        code: 200,
        data: {
          message: '成功'
        }
      }
    },
}